package cwiczenia;

import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileServlet extends HttpServlet {


    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doGet(httpServletRequest, httpServletResponse);    //To change body of overridden methods use File | Settings | File Templates.
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!isLogged(request)) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Login");
            dispatcher.forward(request, response);
        }

        if (request.getParameter("file") == null) {
            response.setContentType("text/html;charset=utf8");
            PrintWriter pw = response.getWriter();
            pw.print(filesToHTML(File.listRoots()));
            pw.close();
        } else {
            File file = new File(request.getParameter("file"));
            if (file.isDirectory()) {
                response.setContentType("text/html;charset=utf8");
                PrintWriter pw = response.getWriter();
                pw.print(filesToHTML(file.listFiles()));
                pw.close();
            }
            if (file.isFile()) {
                response.setContentType("application/x-download");
                response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                OutputStream out = response.getOutputStream();
                returnFile(file.getAbsolutePath(), out);
            }
        }
    }

    private boolean isLogged(HttpServletRequest request) {
        return (request.getSession().getAttribute("login") != null) ? true : false;
    }

    private String filesToHTML(File[] files) {
        StringBuffer sb = new StringBuffer("<html><body><h1>Pliki:</h1>");

        sb.append("<ul>");
        for (File file : files)
            sb.append("<li><a href=\"File?file=" + file.getAbsolutePath() + "\">" + file.getAbsolutePath() + "</a></li>");
        sb.append("</ul>");

        sb.append("</body></html>");

        return sb.toString();
    }

    public static void returnFile(String filename, OutputStream out) throws IOException {
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
            byte[] buf = new byte[4 * 1024];  // 4K buffer
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
        }
        finally {
            if (in != null) in.close();
        }
    }


}
